package cc.dullsky.lucene.operation;

import java.io.IOException;

import org.apache.lucene.document.Document;
import org.apache.lucene.index.Term;
import org.apache.lucene.index.TrackingIndexWriter;
import org.apache.lucene.search.Query;

import cc.dullsky.lucene.manager.IndexManager;

public class IndexOperation {
	private TrackingIndexWriter trackingIndexWriter;
	private String indexName;

	public IndexOperation(String indexName) {
		this.indexName = indexName;
		this.trackingIndexWriter = IndexManager.getIndexManager(indexName).getTrackingIndexWriter();
	}

	/**
	 * 增加索引
	 * 
	 * @param doc
	 * @return boolean 成功true,失败false
	 */
	public boolean addDocument(Document doc) {
		try {
			trackingIndexWriter.addDocument(doc);
			return true;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return false;
	}

	/**
	 * 删除索引
	 * 
	 * @param query
	 * @return boolean 成功true,失败false
	 */
	public boolean deleteDocument(Query query) {
		try {
			trackingIndexWriter.deleteDocuments(query);
			return true;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return false;
	}

	/**
	 * 删除所有索引
	 * 
	 * @return boolean 成功true,失败false
	 */
	public boolean deleteAll() {
		try {
			trackingIndexWriter.deleteAll();
			return true;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return false;
	}

	/**
	 * 更新索引
	 * 
	 * @param term
	 * @param doc
	 * @return boolean 成功true,失败false
	 */
	public boolean updateDocument(Term term, Document doc) {
		try {
			trackingIndexWriter.updateDocument(term, doc);
			return true;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return false;
	}

	/**
	 * 提交
	 */
	public void commit() {
		IndexManager.getIndexManager(indexName).commit();
	}
}
